package com.lnn.handle;

import com.alibaba.fastjson.JSON;
import com.lnn.pojo.dto.Result;
import com.lnn.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: Li Ning Ning
 * @since: 2022/2/28 15:33
 * @version: 1.0
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //在执行controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            //handler 可能是 requestResourceHandler springboot 程序 访问静态资源 默认去classpath下面的static目录去查看
            return true;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            Result result = Result.error();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map == null) {
            Result result = Result.error();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        return true;
    }


}
